<template>
  <Dialog
    v-model="dialogVisible"
    width="1200px"
    title="支付信息审核"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="80px">
      <div class="w-full flex justify-between">
        <div class="w-40%">
          <el-form-item :label="t('wholesalOrder.orderNumber')">
            <el-input v-model="form.order_no" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.userName')">
            <el-input v-model="form.user_name" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.receivingAccountNumber')">
            <el-input v-model="form.pay_account" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.theAmountToBePaid')" prop="payAmount">
            <el-input
              v-model="form.payAmount"
              type="number"
              :placeholder="t('wholesalOrder.theAmountToBePaidMsg')"
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.hashValue')" prop="hash">
            <el-input v-model="form.hash" type="text" :placeholder="t('wholesalOrder.hashValue')" />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.proofOfTransfer')">
            <el-image
              v-if="form.transfer_voucher_url"
              style="width: 100px; height: 100px"
              :preview-teleported="true"
              :src="form.transfer_voucher_url"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[form.transfer_voucher_url]"
              fit="cover"
            />
          </el-form-item>
        </div>
        <div class="w-40%">
          <el-form-item :label="t('wholesalOrder.theTypeOfOrder')">
            <el-input
              :model-value="useEnumeratePicker(orderTypeList, form.order_type)"
              disabled
              placeholder=" "
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.paymentMethods')">
            <el-input
              :model-value="useEnumeratePicker(paymentMethodList, form.payment_method)"
              disabled
              placeholder=" "
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.paymentTime')">
            <el-input v-model="form.pay_time" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.notes')">
            <el-input v-model="form.notes" disabled placeholder=" " />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.currency')">
            <el-input
              disabled
              placeholder=" "
              :model-value="useEnumeratePicker(currencyList, form.currency)"
            />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.total_amount')">
            <el-input disabled placeholder=" " v-model="form.total_amount" />
          </el-form-item>
          <el-form-item :label="t('wholesalOrder.unpaid_amount')">
            <el-input disabled placeholder=" " v-model="form.unpaid_amount" />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit(formRef)"
        >{{ t('wholesalOrder.approved') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { getEnumApi } from '@/api/wholesalOrder'
import { getPayEnumApi, paymentInformationReviewApi } from '@/api/order/pay'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  payment_method: '',
  pay_time: '',
  notes: '',
  transfer_voucher_url: '',
  pay_account: '',
  payAmount: '',
  currency: ''
})

const paymentMethodList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])

const rules = ref<FormRules>({
  payAmount: [
    {
      required: true,
      message: t('wholesalOrder.theAmountToBePaidMsg'),
      trigger: 'blur'
    }
  ]
})

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('支付金额确认之后无法修改，请谨慎操作', t('purchase.logistics.tips'), {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const resp = await paymentInformationReviewApi(form.value.id, {
            pay_amount: form.value.payAmount,
            hash: form.value.hash
          })
          if (resp.code === 0) {
            ElMessage.success('操作成功')
            closeDialog(formEl)
            emit('refresh')
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    payment_method: '',
    pay_time: '',
    notes: '',
    transfer_voucher_url: '',
    pay_account: '',
    payAmount: '',
    hash: ''
  }
  formEl.resetFields()
  dialogVisible.value = false
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

const getBackShow = async (row: Record<string, any>, detail: Record<string, any>) => {
  const resp = await getEnumApi({ field: 'all' })
  paymentMethodList.value = resp.data.pay_method
  currencyList.value = resp.data.currency
  const orderResp = await getPayEnumApi({ field: 'order_type' })
  orderTypeList.value = orderResp.data.order_type
  form.value = row
  form.value.currency = detail.currency
  form.value.total_amount = detail.total_amount
  form.value.unpaid_amount = detail.total_amount - detail.pay_amount
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
